package com.dmbjz.moddymq.task;


import com.dmbjz.moddymq.po.TransMessagePO;
import com.dmbjz.moddymq.service.TransMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


/* 定时处理发送失败消息 */
@EnableScheduling
@Configuration
@Component
@Slf4j
public class ResendTask {

    @Autowired
    private TransMessageService transMessageService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Scheduled(fixedDelayString = "5000")
    //上次任务结束完  5s过后再执行
    public void resendMessage() {

        log.info("定时消息服务启动");
        //1、获取消息事务列表数据
        List<TransMessagePO> messagePOS = transMessageService.listReadyMessages();
        log.info("resendMessage(): messagepos:{}", messagePOS);

        for (TransMessagePO po : messagePOS) {
            log.info("resendMessage(): po:{}", po);
            //2、超过5次不管他
            if (po.getSequence() > 5) {
                log.error("resend too many times!");
                transMessageService.messageDead(po.getId()); //设置为dead
                continue;
            }
            //3、消息配置
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            Message message = new Message(po.getPayload().getBytes(), messageProperties);
            message.getMessageProperties().setMessageId(po.getId());

            //4、发送
            rabbitTemplate.convertAndSend(
                    po.getExchange(),
                    po.getRoutingKey(),
                    message,
                    new CorrelationData(po.getId()));

            log.info("message sent, ID:{}", po.getId());
            //5、发送次数调整
            transMessageService.messageResend(po.getId());
        }

    }


}
